from django.shortcuts import render
from django.views import View
from datetime import timedelta

# 导入序列化器
from . import tasks as TASKS
from mysqldb import tasks as TASKSQL
from .FilterSets import *
from .serializers import *
from iClouds.apidev import redis_key_set

# from iClouds.PulsarSDK import SendAsyncMessage
# from iClouds.PulsarSDK import SendAsyncMessageEx
# from CallManager.tasks import Pulsar_Send

from StaffManager.tasks import Production_points, Membertion_points
from mysqldb import redis as REDIS

# Create your views here.

# 轮询初始值
REDIS.redis_set_key("sysconf", "Count", 0)


class TestViewSet(viewsets.ModelViewSet):
    __title__ = "测试视图"
    __doc__ = f"""
    create:\n
    <h4>会员基础信息</h4>\n
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = NoneSerializer
    queryset = None

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayCallmeConfSetViewSet(viewsets.ModelViewSet):
    __title__ = "呼叫配置"
    __group__ = "呼叫模块"
    __info__ = {"get": "查询场所呼叫配置列表或详情", "post": "创建场所呼叫配置", "put": "编辑场所呼叫配置"}
    __doc__ = """
    list:\n
    <h4>场所呼叫配置列表</h4>
    retrieve:\n
    <h4>场所呼叫配置详情</h4>
    create:\n
    <h4>创建场所呼叫配置</h4>\n
        dispatch = ((0, "前台应答"), (1, "随机派单"), (2, "轮流派单"), (3, "抢单模式"), (4, "固定指派"))
    update:\n
    <h4>编辑场所呼叫配置</h4>
        dispatch = ((0, "前台应答"), (1, "随机派单"), (2, "轮流派单"), (3, "抢单模式"), (4, "固定指派"))
    """
    http_method_names = ["get", "post", "put"]
    authentication_classes = [
        MyJWTAuthentication,
        BarJWTAuthentication,
        WeChatJWTAuthentication,
    ]
    permission_classes = [MyPermissions | BarPermissions | WeChatPermissions]
    serializer_class = AllinpayCallmeConfSerializer
    queryset = AllinpayCallmeConf.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid", "name"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 初始化评价奖励
        # x = AllinpayEvaluateConf.objects.filter(
        #     pid=serializer.data.get("pid")
        # ).values_list("id", flat=True)
        # for i in x:
        #     AllinpayRewardsConf(
        #         eid=i, cid=serializer.data.get("id"), rewards=0, value=0, status=1
        #     ).save()
        # 初始化呼叫技能
        u = AllinpayPlacestaffList.objects.filter(
            pid=serializer.data.get("pid")
        ).values_list("sid", flat=True)
        for i in u:
            AllinpayCallmePost(
                sid=i,
                cid=serializer.data.get("id"),
                pid=serializer.data.get("pid"),
                status=0,
            ).save()
        # # 提交变更缓存
        # if request.user.id < 1000000 and hasattr(serializer.data, "pid"):
        #     redis_key_set(serializer.data.get("pid"), 1, 60 * 10)
        # 发送消息队列
        # SendAsyncMessage(
        #     serializer.data.get("pid"),
        #     "AllinpayCallmeConf",
        #     f'/place/myrole/{serializer.data.get("id")}/',
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        # if request.data.get("name"):
        #     raise serializers.ValidationError({"name": "该字段禁止编辑"})
        # if request.data.get("pid"):
        #     raise serializers.ValidationError({"pid": "该字段禁止编辑"})
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # # 提交变更缓存
        # if request.user.id < 1000000 and hasattr(instance, "pid"):
        #     redis_key_set(instance.pid, 1, 60 * 10)
        # 发送消息队列
        # SendAsyncMessage(
        #     instance.pid,
        #     "AllinpayCallmeConf",
        #     f"/place/myrole/{instance.id}/",
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayRawardModelViewSet(viewsets.ModelViewSet):
    __title__ = "奖励模板"
    __group__ = "奖励模块"
    __info__ = {"get": "查询奖励模板", "post": "创建奖励模板", "put": "编辑奖励模板"}
    __doc__ = """	list:
    <h4>奖励模板列表</h4>
        /place/PlaceRawardList/ 该接口修改raid参数
    retrieve:
    <h4>奖励模板详情</h4>
    create:
    <h4>奖励模板创建</h4>
    update:
    <h4>奖励模板编辑</h4>
    """
    http_method_names = ["get", "post", "put"]
    authentication_classes = [MyJWTAuthentication, BarJWTAuthentication]
    permission_classes = [MyPermissions | BarPermissions]
    serializer_class = AllinpayRawardModelSerializer
    queryset = AllinpayRawardModel.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid", "status"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayCallmePostSetViewSet(viewsets.ModelViewSet):
    __title__ = "呼叫应答配置"
    __group__ = "呼叫模块"
    __info__ = {
        "get": "查询呼叫应答配置列表或详情",
        "post": "创建呼叫应答配置",
        "patch": "编辑呼叫应答配置",
        "delete": "移除呼叫应答配置",
    }
    __doc__ = """
    list:\n
    <h4>呼叫应答配置列表</h4>
    retrieve:\n
    <h4>呼叫应答配置详情</h4>
    create:\n
    <h4>创建呼叫应答配置</h4>\n
    partial_update:\n
    <h4>编辑呼叫应答配置</h4>
    delete:\n
    <h4>移除呼叫应答配置</h4>
    """
    http_method_names = ["get", "post", "patch", "delete"]
    authentication_classes = [
        MyJWTAuthentication,
        BarJWTAuthentication,
        WeChatJWTAuthentication,
    ]
    permission_classes = [MyPermissions | BarPermissions | WeChatPermissions]
    serializer_class = AllinpayCallmePostSerializer
    queryset = AllinpayCallmePost.objects.all()

    filter_backends = [ListDjangoFilterBackend]
    filterset_fields = ["pid", "sid", "cid", "status"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def partial_update(self, request, *args, **kwargs):
        if request.data.get("pid"):
            raise serializers.ValidationError({"pid": "该字段禁止编辑"})
        if request.data.get("sid"):
            raise serializers.ValidationError({"sid": "该字段禁止编辑"})
        if request.data.get("cid"):
            raise serializers.ValidationError({"cid": "该字段禁止编辑"})
        instance = self.get_object()
        partial = True
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class AllinpayCallmeListViewSet(viewsets.ModelViewSet):
    __title__ = "呼叫订单列表"
    __group__ = "呼叫模块"
    __info__ = {"get": "查询场所呼叫列表或详情"}
    __doc__ = """
    list:\n
    <h4>查询呼叫订单列表</h4>
        dispatch = ((0, "前台应答"), (1, "随机派单"), (2, "轮流派单"), (3, "抢单模式"), (4, "固定指派"))
        status = [(0,"新订单"),(1,"应答"),(2, "派单"),(3,"接单"),(4,"完成"),(5,"评价")]
    retrieve:\n
    <h4>查询呼叫订单详情</h4>
    """
    http_method_names = ["get"]
    authentication_classes = [
        MyJWTAuthentication,
        WeChatJWTAuthentication,
        BarJWTAuthentication,
    ]
    permission_classes = [MyPermissions | WeChatPermissions | BarPermissions]
    serializer_class = AllinpayCallmeListSerializer
    queryset = AllinpayCallmeList.objects.all()

    filter_backends = [ListDjangoFilterBackend, SearchFilter]
    # filterset_fields = ["pid"]
    filterset_class = CallmeListFilterSet
    search_fields = ["reqsn", "source"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayCallmeCreatViewSet(viewsets.ModelViewSet):
    __title__ = "创建呼叫订单"
    __group__ = "呼叫模块"
    __info__ = {"post": "创建呼叫订单"}
    __doc__ = """
    create:
    <h4>创建呼叫订单</h4>
    `返回异步会话ID,查询: POST /api/resTasks/ {"celeryID": celeryID}`
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayCallmeCreatSerializer
    queryset = AllinpayCallmeList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(reqsn=has_Reqsn_Callme(), status=0, current=timezone.now())
        # print(serializer.data)
        # 调用异步任务处理订单
        # res = TASKS.Dispatch_Reqsn.apply_async(kwds=serializer.data)
        res = TASKS.Dispatch_Reqsn.apply_async(kwargs=serializer.data).task_id
        # 调用同步任务处理订单
        # res = TASKS.Dispatch_Reqsn(**serializer.data)
        return Response({"rescode": 200, "resmsg": serializer.data, "dispatch": res})


# res = TASKS.Dispatch_Reqsn.apply_async(kwargs={"id": 115})


class AllinpayCallmeReqsnPostViewSet(viewsets.ModelViewSet):
    __title__ = "手动派单"
    __group__ = "呼叫模块"
    __info__ = {"put": "手动派单"}
    __doc__ = """
    update:
    <h4>手动派单</h4>
    """
    http_method_names = ["put"]
    authentication_classes = [MyJWTAuthentication, BarJWTAuthentication]
    permission_classes = [MyPermissions | BarPermissions]
    serializer_class = AllinpayCallmeReqsnPostSerializer
    queryset = AllinpayCallmeList.objects.all()

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save(status=2, answer=request.user.id, antime=timezone.now())

        # 发送微信消息通知
        # callme = AllinpayCallmeList.objects.get(id=instance.id)
        conf = AllinpayCallmeConf.objects.get(id=instance.rtype)
        staff = AllinpayStaffList.objects.get(id=serializer.data.get("target"))
        place = AllinpayPlaceList.objects.get(id=instance.pid)
        timeout = timezone.now() + timedelta(seconds=conf.timeout)

        res = TASKSQL.WeAppsUniformSend.apply_async(
            (
                staff.openid,
                conf.appurl,
                "收到客户新订单通知",
                [
                    instance.reqsn,
                    conf.name,
                    place.name + "_" + instance.source + "号机",
                    timeout.strftime("%Y-%m-%d %H:%M:%S"),
                ],
            )
        )

        return Response({"rescode": 200, "resmsg": res.task_id})


class AllinpayCallmeReqsnOverViewSet(viewsets.ModelViewSet):
    __title__ = "强制结单"
    __group__ = "呼叫模块"
    __info__ = {"put": "强制结单"}
    __doc__ = """
    update:
    <h4>手动结单</h4>
        该状态强制结束呼叫订单，不产生接单奖励。
    """
    http_method_names = ["put"]
    authentication_classes = [MyJWTAuthentication, BarJWTAuthentication]
    permission_classes = [MyPermissions | BarPermissions]
    serializer_class = AllinpayCallmeReqsnOverSerializer
    queryset = AllinpayCallmeList.objects.all()

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save(answer=request.user.id, complete=timezone.now())
        return Response({"rescode": 200, "resmsg": serializer.data})


class AllinpayCallmeReqsnExcetViewSet(viewsets.ModelViewSet):
    __title__ = "评价呼叫"
    __group__ = "呼叫模块"
    __info__ = {"put": "评价呼叫记录"}
    __doc__ = """
    update:
    <h4>评价呼叫记录</h4>
    """
    http_method_names = ["put"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = AllinpayCallmeReqsnExcetSerializer
    queryset = AllinpayCallmeList.objects.all()

    def update(self, request, *args, **kwargs):
        partial = True
        instance = self.get_object()
        if not instance.status == 4:
            raise serializers.ValidationError({"status": "禁止评价"})
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save(evaluate=timezone.now(), status=5)

        try:
            conf = AllinpayCallmeConf.objects.get(id=instance.rtype)
            # rewar = AllinpayRawardList.objects.get(id=types.reward)
        except BaseException as err:
            raise serializers.ValidationError({"reward": "呼叫配置模块异常"})
        else:
            AllinpayCallmeList.objects.update_or_create(
                defaults={"le2": conf.le5}, id=instance.id
            )

        # 创建评价积分派送员工
        res = Production_points.apply_async(
            (
                instance.pid,
                instance.target,
                instance.reqsn,
                conf.name,
                2,
                serializer.data.get("le1"),
            )
        )

        # 创建评价积分派送会员
        rem = Membertion_points.apply_async(
            (
                instance.pid,
                instance.vipid,
                instance.reqsn,
                conf.name,
                3,
                conf.le5,
            )
        )

        # 微信统一模板消息通知
        staff = AllinpayStaffList.objects.get(id=instance.target)
        place = AllinpayPlaceList.objects.get(id=instance.pid)
        timeout = timezone.now() + timedelta(seconds=conf.timeout)
        res = TASKSQL.WeAppsUniformSend.apply_async(
            (
                staff.openid,
                conf.appurl,
                "收到客户新订单通知",
                [
                    instance.reqsn,
                    conf.name + "评价奖励",
                    f'{place.name},{serializer.data.get("le1")}',
                    timeout.strftime("%Y-%m-%d %H:%M:%S"),
                ],
            )
        )
        return Response({"rescode": 200, "resmsg": serializer.data})


# 检查视图
filter_views(globals())
